import Card from "./Card";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Desk extends cc.Component {

    

    bottomCards:QM.Card[] = [];
    outCards:Card[] = [];

    @property(cc.Prefab)
    cardPrefab:cc.Prefab=null;

    bottomParent:cc.Node;
    outParent:cc.Node;

    @property(cc.Label)
    outName:cc.Label=null;

    onLoad () {
        this.bottomParent = this.node.getChildByName("BottomCards");
        this.outParent = this.node.getChildByName("OutCards");
               

        this.bottomParent.removeAllChildren();
        this.outParent.removeAllChildren();

        QM.Socket.Instance.on(this.message,this);

    }

   

    /** 接收底牌 */
    receiveBottomCards(cards:QM.Card[]){
        this.bottomCards = cards;
        cards.forEach(card=>{
            var cardNode = cc.instantiate(this.cardPrefab);            
            cardNode.getComponent(Card).card = card;
            cardNode.parent = this.bottomParent;
        })
    }

    message(obj:QM.QEvent){   
        var cmd = obj.cmd;
        var data = obj.data;
        
        if(cmd && cmd=="receiveOutCards"){
            this.receiveOutCards(data);
        }
    }

    /** 接收出牌 */
    receiveOutCards(obj:{uid:number,cards?:QM.Card[],next?:number}){
        if(!obj.cards) return false;
        this.outParent.removeAllChildren();
        
        var ch = QM.Room.Instance.getCharacterForUid(obj.uid);        
        this.outName.string = ch.username;

        obj.cards.forEach(card=>{
            var node = cc.instantiate(this.cardPrefab);
            var jC = node.getComponent(Card);
            jC.card=card;
            node.parent = this.outParent;
            this.outCards.push(jC);
        })                        
    }    

    reset(){
        this.bottomCards = [];
        this.outCards=[];
        this.outName.string = "";
        this.bottomParent.removeAllChildren();
        this.outParent.removeAllChildren();
    }

    onDestroy(){
        QM.Socket.Instance.off(this.message,this)       ;
    }    
}
